package user;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.swing.JComponent;

/**
 * RestrictionManager represents a list of JComponents that have
 * some sort of user restriction on them. Developers can register
 * a component with this object to ensure that it remains disabled
 * if a user does not have the sufficient privilege level 
 * 
 * @author Enrique De Diego
 *
 */
public class RestrictionManager 
{
	private Map<JComponent,Integer> components;
	private CurrentUser user;
	
	public RestrictionManager(CurrentUser user)
	{
		this.user = user;
		components = new HashMap<JComponent,Integer>();
	}
	
	/**
	 * Register a component as restricted to a certain user level
	 * @param comp - the JComponent to be registered
	 * @param privilege - the level of privilege required for 
	 * this component to be enabled
	 */
	public void registerRestriction(JComponent comp, UserPrivilege privilege)
	{
		if (components.get(comp) == null)
			components.put(comp, privilege.getLevel());
		enforce();	//refresh component list
	}
	
	/**
	 * Removes any restriction on a component. Also
	 * re-enables that component.
	 * @param comp
	 */
	public void unRegisterRestriction(JComponent comp)
	{
		comp.setEnabled(true);
		components.remove(comp);
		enforce();	//refresh components list
	}
	
	/**
	 * Enforce() goes through the list of restricted components
	 * and disables those it finds to be of insufficient privilege level.
	 * It also serves to "refresh" the list after a JComponent has been
	 * added or removed.
	 */
	public void enforce()
	{
		for ( Entry<JComponent, Integer> e : components.entrySet() )
			if (user.isRestricted(e.getValue()))
				e.getKey().setEnabled(false);
			else
				e.getKey().setEnabled(true);
	}
	
}
